package com.sk.bilibili.service;

import com.sk.bilibili.bean.*;
import com.sk.bilibili.event.BiliBiliEvent;
import com.sk.bilibili.other.R;
import com.sk.bilibili.utils.BSessionUtils;
import com.sk.bilibili.utils.RedisUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Service;

/**
 * @author 邵康
 * @date 2021/12/04 18:30
 */
@Service
public class DailyRewardService{

    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private MemberService memberService;
    @Autowired
    private LevelService levelService;

    //  key 为 用户 Id的hash结构
    public R<DailyReward> getDailyReward() {
        String key=String.valueOf(BSessionUtils.getMemberId());
        DailyReward dailyReward = new DailyReward();
        dailyReward.setCoin(redisUtils.getNum(key,"coin"));
        dailyReward.setLogin(redisUtils.contains(key,"login"));
        dailyReward.setDynamic(redisUtils.contains(key,"dynamic"));
        dailyReward.setVideo(redisUtils.contains(key,"video"));
        return R.success(dailyReward);
    }

    //处理每日登录奖励
    @EventListener(condition = "event.type == 'com.sk.bilibili.service.MemberService.dailyLogin'")
    public void handleDailyLogin(BiliBiliEvent<Integer> event){
        Integer memberId = event.getData();
        String key= memberId.toString();
        if(redisUtils.contains(key,"login"))return;
        redisUtils.changeNum(key,"login",2233);//数字  无所谓
        memberService.changeCoin(memberId,2,"每日登录");
        levelService.addExperience(5);
    }

    // 处理投币奖励
    @EventListener(condition = "event.type == 'com.sk.bilibili.service.CoinService.add'")
    public void handleCoinAdd(BiliBiliEvent<Coin> event){
        String key = event.getExtra().get("memberId").toString();
        if(redisUtils.getNum(key,"coin")>=50)return;
        redisUtils.changeNum(key,"coin",1);
        levelService.addExperience(1);
    }

    // 处理观看视频奖励
    @EventListener(condition = "event.type == 'com.sk.bilibili.service.HistoryService.add'")
    public void handleVideoWatch(BiliBiliEvent<History> event){
        History history = event.getData();
        if(history.getType()==6)return;
        addExperience(history.getMemberId(),"video",5);
    }

    // 处理分享动态奖励
    @EventListener(condition = "event.type == 'com.sk.bilibili.service.DynamicService.save'")
    public void handleDynamic(BiliBiliEvent<Dynamic> event){
        Dynamic dynamic = event.getData();//只有  发布视频 或 添加 Note才 有经验
        if(dynamic.getType()>2)return;
        addExperience(dynamic.getMemberId(),"dynamic",5);
    }

    // 通用 布尔型  增加
    private void addExperience(Integer memberId, String field, int experience) {
        String key=memberId.toString();
        if(redisUtils.contains(key,field))return;
        redisUtils.changeNum(key,field,2233);//数字  无所谓
        levelService.addExperience(experience);
    }

}
